from rest_framework import serializers
from django_redis import get_redis_connection


from .utils import check_save_user_token
from users.models import User
from .models import OAuthQQUser, SinaAuthUser


class QQAuthUserSerializer(serializers.Serializer):
    """绑定用户的序列化器"""
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    def validate(self, attrs):   # 此处参数不理解

        access_token = attrs.get('access_token')  # 获取加密的openid 需解密
        openid = check_save_user_token(access_token)
        if not openid:
            raise serializers.ValidationError('openid无效')
        attrs['access_token'] = openid  # 把解密后的openid 保存到反序列化的字典中为后期绑定用户使用

        # 验证短信验证码是否正确
        redis_conn = get_redis_connection('verify_codes')
        # 获取 当前用户的手机号
        mobile = attrs.get('mobile')
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        # 获取前端传的验证码
        sms_code = attrs.get('sms_code')
        if real_sms_code.decode() != sms_code:   # 注意redis 中取出的验证码是bytes类型， 需前处理
            raise serializers.ValidationError('验证码错误')

        try:
            # 判断手机号是已存在用户还是新用户
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 如果异常说明是新用户
            pass
        else:
            # 表示此手机号为已注册用户
            if not user.check_password(attrs.get('password')):
                raise serializers.ValidationError('已存在客户，但密码不正确')
            else:
                attrs['user'] = user
        return attrs


    def create(self, validated_data):
        """把openid和user 进行绑定"""
        user = validated_data.get('user')
        if not user: # 如果用户不存在，那就新增一个用户
            user = User(
                username = validated_data.get('mobile'),
                password = validated_data.get('password'),
                mobile = validated_data.get('mobile')
            )
            user.set_password(validated_data.get('password'))  # 密码加密
            user.save()

        # user and openid 绑定
        OAuthQQUser.objects.create(
            user=user,
            openid=validated_data.get('access_token')
        )
        return user


class SinaAuthUserSerializer(serializers.Serializer):
    """
    Sina登录创建用户序列化器
    """
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')
    # image_code = serializers.CharField(label='图片验证码')

    def validate(self, data):
        # print("data1:",data)
        # 检验access_token
        access_token = data['access_token']
        # 获取身份凭证
        openid = check_save_user_token(access_token)
        if not openid:
            raise serializers.ValidationError('无效的acccess_token')

        # 将'openid'保存
        data['openid'] = openid



        # 校验短信验证码
        mobile = data['mobile']
        sms_code = data['sms_code']
        redis_conn = get_redis_connection('verify_codes')
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if real_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')

        # 如果用户存在,检查用户密码
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 如果出现异常说明是新用户
            pass
        else:
            password = data['password']
            print("password:" , password)
            if not user.check_password(password):
                # print('密码错误')
                raise serializers.ValidationError('密码错误')

            # 将认证后的user保存
            data['user'] = user
        # print("data:" , data)
        return data

    def create(self, validated_data):
        """把openid和user进行绑定"""
        # print("validated_data",validated_data)
        user = validated_data.get('user')
        if not user:  # 如果用户是不存在的,那就新增一个用户
            user = User(
                username=validated_data.get('mobile'),
                password=validated_data.get('password'),
                mobile=validated_data.get('mobile')
            )
            user.set_password(validated_data.get('password'))  # 对密码进行加密
            user.save()
        print(validated_data.get('openid'))
        # 让user和openid绑定
        SinaAuthUser.objects.create(
            user=user,
            access_token=validated_data.get('openid')
        )

        return user